<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>4 给滚动行为添加节流</title>
  <style>
    .box-wrapper {
      width: 200px;
      height: 200px;
      overflow: auto;
      border: solid 1px pink;
    }

    .box {
      width: 200px;
      height: 2000px;
    }
  </style>
</head>

<body>
  <div class="box-wrapper">
    <div class="box"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Similique nobis cumque omnis ducimus
    </div>
  </div>

  <script>
    let boxWrapper = document.querySelector('.box-wrapper');

    function fn() {
      // console.log(ev)
      console.log('fn...')
    }

    function throttle(func, wait = 300) {
      let timer = null,
        previous = 0; // 记录上一次操作的时间
      return function anonymous(...params) {
        let now = new Date,
          remaining = wait - (now - previous); // remaining差值 记录还差多久到达我们一次触发的频率
        if (remaining <= 0) {
          // 两次的间隔时间已经超过wait
          window.clearTimeout(timer);
          timer = null;
          previous = now;
          func.call(this, ...params);
        } else if (!timer) {
          timer = setTimeout(() => {
            // 两次的间隔时间还不符合触发的频率
            timer = null;
            previous = new Date;
            func.call(this, ...params);
          }, remaining);
        }
      };
    }

    boxWrapper.addEventListener("scroll", throttle(fn, 100))
  </script>
</body>

</html>